package com.atguigu.serviceedu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.service.handler.GuliException;
import com.atguigu.serviceedu.entity.EduSubject;
import com.atguigu.serviceedu.entity.excel.SubjectExcel;
import com.atguigu.serviceedu.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @Classname SubjectExcelListener
 * @Description TODO
 * @Date 2022/8/29 11:03
 * @Created by ZHL17
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectExcel> {

    private EduSubjectService subjectService;
    @Override
    public void invoke(SubjectExcel subjectExcel, AnalysisContext analysisContext) {
           if(subjectExcel==null){
               throw new GuliException(20001,"添加失败");
           }
           readSubject(this.subjectService,subjectExcel);
    }

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    public void readSubject(EduSubjectService subjectService,SubjectExcel subjectExcel){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",subjectExcel.getOneSubject());
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        if(oneSubject==null){
            oneSubject=new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectExcel.getOneSubject());
            subjectService.save(oneSubject);
        }
        String id = oneSubject.getId();
        this.twoSubject(subjectService,subjectExcel,id);
    }
    public void twoSubject(EduSubjectService subjectService,SubjectExcel subjectExcel,String id){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",subjectExcel.getTwoSubject());
        wrapper.eq("parent_id",id);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        if(twoSubject==null){
            EduSubject eduSubject=new EduSubject();
            eduSubject.setParentId(id);
            eduSubject.setTitle(subjectExcel.getTwoSubject());
            subjectService.save(eduSubject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
